<?php

/**
 * 
 * @author yuxun
 *
 */
class MatchCrossServerVService extends Service{

    public static function indexHeader($typeIndex){
        $header = array(
                'id'            => array('text' => '序号', 'width' => '80px'),
        		'cross_server_name'       => array('text' => '跨服名称', 'width' => '150px'),
                'server_list'   => array('text' => '包含服务器', 'width' => '300px'),
        		'node_name'     => array('text' => '节点名称', 'width' => '150px'),
        		'develop_id'    => array('text' => '开发ID', 'width' => '100px'),
        		'version'       => array('text' => '版本', 'width' => '60px'),
        		'ip'            => array('text' => 'IP', 'width' => '100px'),
        		'port'          => array('text' => '端口', 'width' => '80px'),
        		'reset_time'    => array('text' => '重置时间', 'width' => '150px'),
        		'status'        => array('text' => '重置状态', 'width' => '100px'),
        		'create_time'   => array('text' => '创建时间', 'width' => '150px'),
                'action'        => array('text' => '操作', 'width' => '60px'),
        );
        if($typeIndex == 'handIndex'){
        	unset($header['reset_time']);
        }

        return $header;
    }
    
    public static function indexData($params,$typeIndex){   	
    	$modMatchCrossServerV = new ModMatchCrossServerV();
        $result = $modMatchCrossServerV->page($params);
        $crossList = SystemService::searchInfo('cross');
        $reset_time = $crossList['reset_time'];
    	$length = count($result['data']);
    	$synList = self::synList();
    	foreach($result['data'] as $k=>&$v){
    		$type = 1;
    		if($k == 0 && $length == 1){  //当前页只剩下一条数据时，删除之后需显示上一页的数据
    			$type = 2;
    		}  
    		$server_list =  self::getServer($v['id']); 		
    		$v['server_list'] = $server_list == ''? '':$server_list;
    	    $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
    		$v['reset_time']     = $reset_time;
    		$v['action']        .= ' <a href="'.PubFunc::buildBackUrl('/oss/?r=matchCrossServerV/edit').'&id='.$v['id'].'">编辑</a>';
    		$v['action']        .= ' <a href="'.PubFunc::buildBackUrl('/oss/?r=matchCrossServerV/delete',$type).'&id='.$v['id'].'" onclick="del()" confirm="是否要删除该条服信息?">删除</a>';
    		$v['status'] = $synList[$v['status']];
    		
    		if($typeIndex == 'handIndex'){
    			$id = $v['id'];
    			$checkbox = '<input value="'.$v['id'].'"  name="id" type="checkbox">&nbsp;&nbsp;';
    			$v['id'] = $checkbox.$v['id'];
    		}
    		
    	}
    	unset($v);
    
    	return $result;
    }
    
    public static function getServer($id){  	
    	$modMatchCrossSerV = new ModMatchCrossSerV();
    	$serverData = $modMatchCrossSerV->getServer($id);
    	$list = '';
    	foreach ($serverData as $key=>$val){
    		$list .= ','.$val['server_name'].'('.$val['server_num'].')';
    	}
    	$list = substr($list, 1);
    	return $list;
    }
    
    public static function get($id){
    	$modMatchCrossServerV = new ModMatchCrossServerV();
    	$obj = $modMatchCrossServerV->findByPk($id);
    	if($obj){
    		$info = $obj->getAttributes();   
    		return $info;
    	}else{
    		return false;
    	}
    }
    
    /*
     * 查询能够让匹配跨服选择的服（去除$id本身的关系的服务器）
     */
    public static function fitServer($id){
    	$game = PubBase::getCurrentGame();
    	//查询除了本身之外的其他服与跨服的关系
    	$otherInfoServer = self::getOtherMatchServer($id);
    	$server_ids = '';
    	foreach ($otherInfoServer as $key=>$val){
    		$server_ids .= $val['server_id'] . ', ';
    		if($val['match_id'] == $id){
    			unset($otherInfoServer[$key]);  //unset本身
    		}
    	}
    	$server_ids = substr($server_ids,0,strlen($server_ids)-2);
    	if($server_ids == ''){
    		$server_ids = 0;
    	}
    	
    	//查询在常规跨服的服务器
    	$modRoutineCrossSer = new ModRoutineCrossSer();
    	$routineServerList = $modRoutineCrossSer->getRoutineServer($game);
    	$$routineServer_array = array();
    	foreach ($routineServerList as $key=>$val){
    		$routineServer_array[] = $val['server_id'];
    	}   	
    	
    	//根据$server_ids查询没有加入匹配跨服的服数据(剔除 测试服（备选服也是测试服）、审核服 )
    	$modServer = new ModServer();
    	$noInfoServer = $modServer->getServerForNorinIds($game,$server_ids);
    	foreach ($noInfoServer as $key=>$val){
    		if($val['check_flag'] == 1 || $val['check_flag'] == 3){
    			continue;
    		}
    		if(in_array($val['id'], $routineServer_array)){ //在常规跨服的服务器
    			continue;
    		}
    		$d = array();
    		$d['match_id'] = 0;
    		$d['server_id'] = $val['id'];
    		$d['id'] = 0;
    		$d['server_name'] = $val['server_name'];
    		$d['server_num'] = $val['server_num'];
    		$d['cross_server_name'] = '';
    		$otherInfoServer[] = $d;
    	}
    	return $otherInfoServer;
    }
    
    /**
     * 根据主键id获取其关联的服务器
     */
    public static function getMatchServer($id){
    	$modMatchCrossSerV = new ModMatchCrossSerV();
    	$serverData = $modMatchCrossSerV->getServer($id);
    	return $serverData;
    }
    
    /**
     * 获取!=id的另外其他匹配跨服下的服务器
     * @param unknown $id
     * @return unknown
     */
    public static function getOtherMatchServer(){
    	$game = PubBase::getCurrentGame();
    	$modMatchCrossSerV = new ModMatchCrossSerV();
    	$serverData = $modMatchCrossSerV->getOtherMatchServer($game);
    	return $serverData;
    }
   
    /*
     * 去重
     */
    public static function crepeat($id = 0, $field, $val,$g){
    	$modMatchCrossServerV = new ModMatchCrossServerV();
    	$conut = $modMatchCrossServerV->crepeat($id, $field, $val,$g);
    	return $conut;
    }

    public static function doAdd($params){
    	$user = AccAuth::me();
    	$modMatchCrossServerV = new ModMatchCrossServerV();
    	$modMatchCrossServerV->game = $params['g'];;
    	$modMatchCrossServerV->cross_server_name = $params['cross_server_name'];
    	$modMatchCrossServerV->node_name = $params['node_name'];
    	$modMatchCrossServerV->ip = $params['ip'];
    	$modMatchCrossServerV->port = $params['port'];
    	$modMatchCrossServerV->create_user   = $user['UserID'];
    	$modMatchCrossServerV->create_time   = time();
    	$modMatchCrossServerV->update_user   = $user['UserID'];
    	$modMatchCrossServerV->update_time   = time();
    	$modMatchCrossServerV->version = $params['version'];
    	$modMatchCrossServerV->develop_id = $params['develop_id'];
    	$result = $modMatchCrossServerV->save();
    	$match_id = $modMatchCrossServerV->id;
    	if($result !== false){
    		$vids = $params['vids'];
    		$match_ids = $params['match_ids'];
    		$server_ids = $params['server_ids'];
    		$vids_array = explode(',', $vids);
    		$match_ids_array = explode(',', $match_ids);
    		$server_ids_array = explode(',', $server_ids);
    		//将vid不等于0的删除与匹配跨服的关系，将等于0的删除与常规跨服的关系
    		$m_ids = '';
    		$ser_ids = '';
    		foreach ($vids_array as $key=>$val){
    			if($val != 0){
    				$m_ids .= ','.$val;
    			}
    			if($val == 0){
    				$ser_ids .= ','.$server_ids_array[$key];
    			}
    		}
    		$m_ids = substr($m_ids, 1);
    		$ser_ids = substr($ser_ids, 1);
    		 
    		//先删除本身的关系
    		$modMatchCrossSerV = new ModMatchCrossSerV();
    		$modMatchCrossSerV->deleteAll('match_id=:match_id', array(':match_id'=>$id));
    		//删除被选进来的其他匹配跨服的服务器关系
    		if($m_ids != ''){
    			$modMatchCrossSerV->deleteForIds($m_ids);
    		}
    		//删除被选进来的常规跨服的服务器关系
//     		$modRoutineCrossSer = new ModRoutineCrossSer();
//     		if($ser_ids != ''){
//     			$modRoutineCrossSer->deleteForServerIds($ser_ids);
//     		}
    		//最后将新的关系加入
    		$server = array();
    		foreach ($server_ids_array as $key=>$val){
    			$data = array();
    			$data['server_id'] = $val;
    			$data['match_id'] = $match_id;
    			array_push($server, $data);
    		}
    		$modMatchCrossSerV->addmuch($server);
    	}
    	return $result;
    	
    }
    
    public static function doEdit($id, $params){
        if(empty($id)) return array('state'=>false,'msg'=>'非法参数');
        $user = AccAuth::me();

        $modMatchCrossServerV = new ModMatchCrossServerV();
        $update = array();
        $update['game']         = $params['g'];
        $update['cross_server_name']  = $params['cross_server_name'];
        $update['node_name']       = $params['node_name'];
        $update['ip']       = $params['ip'];
        $update['port']       = $params['port'];
        $update['update_user']  = $user['UserID'];
        $update['update_time']  = time();
        $update['version'] = $params['version'];
        $update['develop_id'] = $params['develop_id'];
        $result = $modMatchCrossServerV->updateByPk($id, $update);
        if($result !== false){
        	$vids = $params['vids'];
        	$match_ids = $params['match_ids'];
        	$server_ids = $params['server_ids'];
        	$vids_array = explode(',', $vids);
        	$match_ids_array = explode(',', $match_ids);
        	$server_ids_array = explode(',', $server_ids);
        	//将vid不等于0的删除与匹配跨服的关系，将等于0的删除与常规跨服的关系
        	$m_ids = '';
        	$ser_ids = '';
        	foreach ($vids_array as $key=>$val){        		
        		if($val != 0){
        			$m_ids .= ','.$val;
        		} 
        		if($val == 0){
        			$ser_ids .= ','.$server_ids_array[$key];
        		}       		
        	}
        	$m_ids = substr($m_ids, 1);
        	$ser_ids = substr($ser_ids, 1);
        	
        	//先删除本身的关系
        	$modMatchCrossSerV = new ModMatchCrossSerV();
        	$modMatchCrossSerV->deleteAll('match_id=:match_id', array(':match_id'=>$id));
        	//删除被选进来的其他匹配跨服的服务器关系
        	if($m_ids != ''){
        		$modMatchCrossSerV->deleteForIds($m_ids);
        	}
        	//删除被选进来的常规跨服的服务器关系
//         	$modRoutineCrossSer = new ModRoutineCrossSer();
//         	if($ser_ids != ''){
//         		$modRoutineCrossSer->deleteForServerIds($ser_ids);
//         	}
        	//最后将新的关系加入
        	$server = array();
        	foreach ($server_ids_array as $key=>$val){
        		$data = array();
        		$data['server_id'] = $val;
        		$data['match_id'] = $id;
        		array_push($server, $data);
        	}
        	$modMatchCrossSerV->addmuch($server);
        }
        return $result;
        
    }
    
    public static function delete($id){
    	if(empty($id)) return false;
    
    	$modMatchCrossServerV = new ModMatchCrossServerV();
    	$modMatchCrossServerV->deleteByPk($id);
    	 
    	//删除常规跨服服务器与服务器的关系
    	$modMatchCrossSerV = new ModMatchCrossSerV();
    	$modMatchCrossSerV->deleteAll('match_id=:match_id', array(':match_id'=>$id));
    	 
    	return true;
    }
    
    
    /**
     * 查询已经被使用的了服
     * @param unknown $routine_id
     * @return multitype:unknown
     */
    public static function useServer($match_id){
    	$modMatchCrossSerV = new ModMatchCrossSerV();
    	$useList_obj = $modMatchCrossSerV->getUseServer($match_id);
    	$useList = array();
    	foreach ($useList_obj as $key=>$val){
    		$useList[] = $val['server_id'];
    	}

    	return $useList;
    }
    
    public static function synList(){
    	return array(
    			'1' => '未重置',
    			'2' => '重置成功',
    			'3' => '重置失败',
    	);
    }
    
    public static function getServerName($id){
    	$modMatchCrossSerV = new ModMatchCrossSerV();
    	$serverData = $modMatchCrossSerV->getServer($id);
    	$list = array();	
    	foreach ($serverData as $key=>$val){
    		$list[] = $val['name'];
    	}
    	return $list;
    }
    
    public static function commonformal($match_obj){
    	$modMatchCrossServerV = new ModMatchCrossServerV();
    	$modMatchCrossSerV = new ModMatchCrossSerV();
    	//同步start
    	$params = array();
    	$upids = '';
    	foreach ($match_obj as $key=>$val){
    		$upids .= ','.$val['id'];
    		$match_id = $val['id'];
    		$match_server_obj = $modMatchCrossSerV->findAllByAttributes(array('match_id'=>$match_id));
    		$match_server_ids = '';
    		if(!$match_server_obj){  //若没有关系，则退出循环
    			//直接删除数据
    			$modMatchCrossServerV->deleteByPk($val['id']);
    			continue;
    		}
    	
    		$version = $val['version'];
    		$crossnode = $val['node_name'];
    		$gamenodes = self::getServerName($val['id']);
    		$d = array();
    		$d['version'] = $version;
    		$d['crossnode'] = $crossnode;
    		$d['gamenodes'] = $gamenodes;
    	
    		$extend_data = array();
    		$extend_data['ip'] = $val['ip'];
    		$extend_data['port'] = $val['port'];
    		$d['extend_data'] = $extend_data;
    		$params[$crossnode] = $d;
    	}
    	//echo '<pre/>';var_dump($params);exit;
    	$send_out = RoutineCrossServerService::send($params,1);
    	//同步end
    	if($send_out['status'] == 1){  //成功
    		$ids = '';
    		foreach ($match_obj as $key=>$val){
    			$match_id = $val['id'];
    			$match_server_obj = $modMatchCrossSerV->findAllByAttributes(array('match_id'=>$match_id));
    			if(!$match_server_obj){  //若没有关系，则退出循环
    				continue;
    			}
    			 
    			$ids .= ','.$val['id'];
    			//将匹配跨服加到正式的匹配跨服表
    			$modMatchCrossServer = new ModMatchCrossServer();
    			$modMatchCrossServer->game = $val['game'];
    			$modMatchCrossServer->cross_server_name = $val['cross_server_name'];
    			$modMatchCrossServer->node_name = $val['node_name'];
    			$modMatchCrossServer->ip = $val['ip'];
    			$modMatchCrossServer->port = $val['port'];
    			$modMatchCrossServer->version = $val['version'];
    			$modMatchCrossServer->develop_id = $val['develop_id'];
    			$modMatchCrossServer->create_user   = $user['UserID'];
    			$modMatchCrossServer->create_time   = time();
    			$modMatchCrossServer->update_user   = $user['UserID'];
    			$modMatchCrossServer->update_time   = time();
    			$mmresult = $modMatchCrossServer->save();
    			if($mmresult !== false){
    				$matchCrossSerData = array();
    				foreach ($match_server_obj as $k=>$v){
    					$d = array();
    					$d['match_id'] = $modMatchCrossServer->id;
    					$d['server_id'] = $v['server_id'];
    					array_push($matchCrossSerData, $d);
    				}
    				$modMatchCrossSer = new ModMatchCrossSer();
    				$modMatchCrossSer->addmuch($matchCrossSerData);
    			}
    		}
    	
    		//删除发送成功的匹配跨服数据（未生效表）
    		$ids = substr($ids, 1);
    		$modMatchCrossServerV->deleteForIds($ids);
    		$modMatchCrossSerV->deleteForMatchIds($ids);
    		$out = array('status'=>1,'msg'=>'匹配跨服配置生效成功','data'=>'');
    		return $out;
    	
    	}else{//失败
    		$upids = substr($upids, 1);
    		$modMatchCrossServerV->updateRoutineForIds(3,$upids);
    		$out = array('status'=>0,'msg'=>$send_out['msg'],'data'=>'');
    		return $out;
    	}
    }
    
    public static function handformal($ids){
    	$user = AccAuth::me();
    	$game = PubBase::getCurrentGame();
    	$crossList = SystemService::searchInfo('cross');
    	$reset_time = $crossList['reset_time'];
    	$reset_time_2 = strtotime($reset_time);
    	$reset_time_2 = $reset_time_2 + 60*60*2;
    	$reset_time_1 = strtotime ("-3 day", strtotime($reset_time));
    	$nowTime = strtotime(date('Y-m-d H:i:00',time()));
    	if($reset_time_1 < $nowTime && $nowTime < $reset_time_2){  //重置时间的前3天内
    		$out = array('status'=>0,'msg'=>'现在不是临时操作时间','data'=>'');
    		return $out;
    	}
    	
    	$modMatchCrossServerV = new ModMatchCrossServerV();
    	$modMatchCrossSerV = new ModMatchCrossSerV();
    	//$match_obj = $modMatchCrossServerV->findAllByAttributes(array('game'=>$game));
    	$match_obj = $modMatchCrossServerV->getMatchForIds($ids);
    	
    	if(!$match_obj){
    		$out = array('status'=>0,'msg'=>'暂无数据','data'=>'');
    		return $out;
    	}
    	
    	$out = self::commonformal($match_obj);
    	return $out;
    }
    
    public static function formal(){
    	$user = AccAuth::me();
    	$game = PubBase::getCurrentGame();
    	$crossList = SystemService::searchInfo('cross');
    	$reset_time = $crossList['reset_time'];
    	$reset_time_2 = strtotime($reset_time);
    	$reset_time_2 = $reset_time_2 + 60*60*2;
    	$reset_time_1 = strtotime ("-3 day", strtotime($reset_time));
    	$nowTime = strtotime(date('Y-m-d H:i:00',time()));
    	if($reset_time_1 > $nowTime || $nowTime > $reset_time_2){  //未在重置时间的前3天内的
    		$out = array('status'=>0,'msg'=>'还未到可以操作的时间','data'=>'');
    		return $out;	
    	}
    	
    	$modMatchCrossServerV = new ModMatchCrossServerV();
    	$modMatchCrossSerV = new ModMatchCrossSerV();
    	$match_obj = $modMatchCrossServerV->findAllByAttributes(array('game'=>$game));
    		
    	if(!$match_obj){
    		$out = array('status'=>0,'msg'=>'暂无数据','data'=>'');
    		return $out;
    	}else{
    		//将正式的匹配跨服is_delete修改为1
    		$modMatchCrossServer = new ModMatchCrossServer();
    		$modMatchCrossServer->updateAll(array('is_delete'=>1,'update_time'=>time(),'update_user'=>$user['UserID']),'game =:game and is_delete=:is_delete',array(':game'=>$game,':is_delete'=>0));
    	}
    	
    	//同步start
    	$params = array();
    	$upids = '';
    	foreach ($match_obj as $key=>$val){	
    		$upids .= ','.$val->id;
    		$match_id = $val->id;
    		$match_server_obj = $modMatchCrossSerV->findAllByAttributes(array('match_id'=>$match_id));
    		$match_server_ids = '';
    		if(!$match_server_obj){  //若没有关系，则退出循环
    			//直接删除数据
    			$modMatchCrossServerV->deleteByPk($val->id);
    			continue;
    		}
    		
    		$version = $val->version;
    		$crossnode = $val->node_name;
    		$gamenodes = self::getServerName($val->id);
    		$d = array();
    		$d['version'] = $version;
    		$d['crossnode'] = $crossnode;
    		$d['gamenodes'] = $gamenodes;
    		
    		$extend_data = array();
    		$extend_data['ip'] = $val->ip;
    		$extend_data['port'] = $val->port;
    		$d['extend_data'] = $extend_data;
    		$params[$crossnode] = $d;
    	}
    	$send_out = RoutineCrossServerService::send($params,1);
    	//同步end
    	if($send_out['status'] == 1){  //成功
    		$ids = '';
    		foreach ($match_obj as $key=>$val){
    			$match_id = $val->id;
    			$match_server_obj = $modMatchCrossSerV->findAllByAttributes(array('match_id'=>$match_id));
    			if(!$match_server_obj){  //若没有关系，则退出循环
    				continue;
    			}
    			
    			$ids .= ','.$val->id;
    			//将匹配跨服加到正式的匹配跨服表
    			$modMatchCrossServer = new ModMatchCrossServer();
    			$modMatchCrossServer->game = $val->game;
    			$modMatchCrossServer->cross_server_name = $val->cross_server_name;
    			$modMatchCrossServer->node_name = $val->node_name;
    			$modMatchCrossServer->ip = $val->ip;
    			$modMatchCrossServer->port = $val->port;
    			$modMatchCrossServer->version = $val->version;
    			$modMatchCrossServer->develop_id = $val->develop_id;
    			$modMatchCrossServer->create_user   = $user['UserID'];
    			$modMatchCrossServer->create_time   = time();
    			$modMatchCrossServer->update_user   = $user['UserID'];
    			$modMatchCrossServer->update_time   = time();
    			$mmresult = $modMatchCrossServer->save();
    			if($mmresult !== false){
    				$matchCrossSerData = array();
    				foreach ($match_server_obj as $k=>$v){
    					$d = array();
    					$d['match_id'] = $modMatchCrossServer->id;
    					$d['server_id'] = $v['server_id'];
    					array_push($matchCrossSerData, $d);
    				}
    				$modMatchCrossSer = new ModMatchCrossSer();
    				$modMatchCrossSer->addmuch($matchCrossSerData);
    			}
    		}
    		
    		//删除发送成功的匹配跨服数据（未生效表）
    		$ids = substr($ids, 1);
    		$modMatchCrossServerV->deleteForIds($ids);
    		$modMatchCrossSerV->deleteForMatchIds($ids);
    		$out = array('status'=>1,'msg'=>'匹配跨服配置生效成功','data'=>'');
    		return $out;

    	}else{//失败
    		$upids = substr($upids, 1);
    		$modMatchCrossServerV->updateRoutineForIds(3,$upids);
    		$out = array('status'=>0,'msg'=>$send_out['msg'],'data'=>'');
    		return $out;
    	}
    	
    }
    

}